#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpServer = new QTcpServer();

    tcpServer->listen(QHostAddress("192.168.6.72"),8888);

    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newClientLink()));

}

MainWindow::~MainWindow()
{
    qDeleteAll(formList);
    formList.clear();
    tcpServer->close();
    delete ui;
}

void MainWindow::newClientLink()
{
    QTcpSocket* tcpsock = tcpServer->nextPendingConnection();

    QString clientInfo = QString("%1:%2")
            .arg(tcpsock->peerAddress().toString())
            .arg(tcpsock->peerPort());

    ui->listWidget->addItem(clientInfo);
    Form * newForm = new Form(ui->widget,tcpsock);
    tcpsock->setParent(newForm);
    formList.append(newForm);

    connect(newForm, &Form::clientDisconnected, this, [=](Form *form) {
        int index = formList.indexOf(form);
        if (index == -1) return;

        // 删除列表项
        QListWidgetItem *item = ui->listWidget->takeItem(index);
        delete item;

        // 移除并删除Form
        formList.removeAt(index);
        form->deleteLater();

        // 修正lastRow
        if (lastRow == index) {
            lastRow = -1;
        } else if (lastRow > index) {
            lastRow--;
        }
    });
}


void MainWindow::on_listWidget_currentRowChanged(int currentRow)
{
    if(lastRow != -1 && lastRow < formList.size())
        {
            Form* prevForm = formList.at(lastRow);
            if (prevForm) prevForm->hide();  // 检查指针非空
        }

        // 显示当前窗口（检查索引有效性）
        if(currentRow != -1 && currentRow < formList.size())
        {
            Form* currForm = formList.at(currentRow);
            if (currForm) currForm->show();
        }

        lastRow = currentRow;
}
